Q-4: Attempt the following (Any two) (10 Marks)
Questions
A: How can you add, update, and delete preferences in an Android app?
B: Explain how to draw shapes using Canvases and Paints in Android.
C: Explain the concept of Radio Groups and how they are implemented in Android.
Answer A: Add, Update, and Delete Preferences in Android
Android SharedPreferences provide a way to store and retrieve key-value pairs persistently. Here's how to perform CRUD operations:
1. Getting SharedPreferences Instance
// Method 1: Activity-specific preferences
SharedPreferences preferences = getPreferences(Context.MODE_PRIVATE);
// Method 2: Application-wide preferences
SharedPreferences preferences = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
// Method 3: Default shared preferences
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
2. Adding/Updating Preferences
public class PreferenceManager {
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
public PreferenceManager(Context context) {
sharedPreferences = context.getSharedPreferences("UserPrefs", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
}
// Add/Update String preference
public void saveString(String key, String value) {
editor.putString(key, value);
editor.apply(); // or editor.commit()
}
// Add/Update Integer preference
public void saveInt(String key, int value) {
editor.putInt(key, value);
editor.apply();
}
// Add/Update Boolean preference
public void saveBoolean(String key, boolean value) {
editor.putBoolean(key, value);
editor.apply();
}
// Add/Update Float preference
public void saveFloat(String key, float value) {
editor.putFloat(key, value);
editor.apply();
}
// Add/Update Long preference
public void saveLong(String key, long value) {
editor.putLong(key, value);
editor.apply();
}
// Add/Update Set of Strings
public void saveStringSet(String key, Set<String> values) {
editor.putStringSet(key, values);
editor.apply();
}
}
3. Reading Preferences
public class PreferenceManager {
// ... previous code ...
// Read String preference
public String getString(String key, String defaultValue) {
return sharedPreferences.getString(key, defaultValue);
}
// Read Integer preference
public int getInt(String key, int defaultValue) {
return sharedPreferences.getInt(key, defaultValue);
}
// Read Boolean preference
public boolean getBoolean(String key, boolean defaultValue) {
return sharedPreferences.getBoolean(key, defaultValue);
}
// Read Float preference
public float getFloat(String key, float defaultValue) {
return sharedPreferences.getFloat(key, defaultValue);
}
// Read Long preference
public long getLong(String key, long defaultValue) {
return sharedPreferences.getLong(key, defaultValue);
}
// Read Set of Strings
public Set<String> getStringSet(String key, Set<String> defaultValue) {
return sharedPreferences.getStringSet(key, defaultValue);
}
// Check if key exists
public boolean contains(String key) {
return sharedPreferences.contains(key);
}
// Get all preferences
public Map<String, ?> getAllPreferences() {
return sharedPreferences.getAll();
}
}
4. Deleting Preferences
public class PreferenceManager {
// ... previous code ...
// Delete specific preference
public void deletePreference(String key) {
editor.remove(key);
editor.apply();
}
// Delete multiple preferences
public void deletePreferences(String... keys) {
for (String key : keys) {
editor.remove(key);
}
editor.apply();
}
// Clear all preferences
public void clearAllPreferences() {
editor.clear();
editor.apply();
}
}
5. Practical Implementation Example
public class UserPreferences {
private static final String PREF_NAME = "UserSettings";
private static final String KEY_USERNAME = "username";
private static final String KEY_EMAIL = "email";
private static final String KEY_IS_LOGGED_IN = "is_logged_in";
private static final String KEY_THEME = "theme";
private static final String KEY_NOTIFICATIONS = "notifications";
private SharedPreferences preferences;
private SharedPreferences.Editor editor;
public UserPreferences(Context context) {
preferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
editor = preferences.edit();
}
// Save user login data
public void saveUserData(String username, String email) {
editor.putString(KEY_USERNAME, username);
editor.putString(KEY_EMAIL, email);
editor.putBoolean(KEY_IS_LOGGED_IN, true);
editor.apply();
}
// Update user profile
public void updateUsername(String newUsername) {
editor.putString(KEY_USERNAME, newUsername);
editor.apply();
}
// Get user data
public String getUsername() {
return preferences.getString(KEY_USERNAME, "");
}
public String getEmail() {
return preferences.getString(KEY_EMAIL, "");
}
public boolean isLoggedIn() {
return preferences.getBoolean(KEY_IS_LOGGED_IN, false);
}
// Save app settings
public void saveTheme(String theme) {
editor.putString(KEY_THEME, theme);
editor.apply();
}
public void setNotificationsEnabled(boolean enabled) {
editor.putBoolean(KEY_NOTIFICATIONS, enabled);
editor.apply();
}
// Get app settings
public String getTheme() {
return preferences.getString(KEY_THEME, "light");
}
public boolean areNotificationsEnabled() {
return preferences.getBoolean(KEY_NOTIFICATIONS, true);
}
// Logout user (delete user-specific data)
public void logout() {
editor.remove(KEY_USERNAME);
editor.remove(KEY_EMAIL);
editor.putBoolean(KEY_IS_LOGGED_IN, false);
editor.apply();
}
// Reset all settings
public void resetSettings() {
editor.clear();
editor.apply();
}
}
6. Using in Activity
public class MainActivity extends AppCompatActivity {
private UserPreferences userPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userPreferences = new UserPreferences(this);
// Save preferences
userPreferences.saveUserData("john_doe", "john@email.com");
userPreferences.saveTheme("dark");
userPreferences.setNotificationsEnabled(true);
// Read preferences
String username = userPreferences.getUsername();
String theme = userPreferences.getTheme();
boolean isLoggedIn = userPreferences.isLoggedIn();
// Update preferences
userPreferences.updateUsername("john_smith");
// Delete specific preference
userPreferences.logout();
// Clear all preferences
userPreferences.resetSettings();
}
}
7. Preference Change Listener
public class MainActivity extends AppCompatActivity {
private SharedPreferences.OnSharedPreferenceChangeListener preferenceChangeListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences preferences = getSharedPreferences("MyPrefs", MODE_PRIVATE);
// Create preference change listener
preferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
switch (key) {
case "theme":
String newTheme = sharedPreferences.getString(key, "light");
applyTheme(newTheme);
break;
case "notifications":
boolean notificationsEnabled = sharedPreferences.getBoolean(key, true);
toggleNotifications(notificationsEnabled);
break;
}
}
};
// Register listener
preferences.registerOnSharedPreferenceChangeListener(preferenceChangeListener);
}
@Override
protected void onDestroy() {
super.onDestroy();
// Unregister listener to prevent memory leaks
SharedPreferences preferences = getSharedPreferences("MyPrefs", MODE_PRIVATE);
preferences.unregisterOnSharedPreferenceChangeListener(preferenceChangeListener);
}
private void applyTheme(String theme) {
// Apply theme changes
}
private void toggleNotifications(boolean enabled) {
// Handle notification settings
}
}
Answer B: Drawing Shapes using Canvases and Paints in Android
Canvas and Paint are fundamental classes for custom drawing in Android:
1. Understanding Canvas and Paint
Canvas: A drawing surface that provides methods for drawing shapes, text, and bitmaps. Paint: Defines the style and color information for drawing operations.
2. Basic Setup for Custom Drawing
public class CustomDrawingView extends View {
private Paint paint;
private Canvas canvas;
public CustomDrawingView(Context context) {
super(context);
init();
}
public CustomDrawingView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
paint = new Paint();
paint.setAntiAlias(true); // Smooth edges
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
this.canvas = canvas;
drawShapes();
}
private void drawShapes() {
// Drawing methods will be implemented here
}
}
3. Paint Configuration
private void configurePaint() {
// Basic paint properties
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.FILL); // FILL, STROKE, FILL_AND_STROKE
paint.setStrokeWidth(5f);
paint.setAntiAlias(true);
// Advanced paint properties
paint.setAlpha(128); // Transparency (0-255)
paint.setStrokeCap(Paint.Cap.ROUND); // Line end caps
paint.setStrokeJoin(Paint.Join.ROUND); // Line joins
paint.setPathEffect(new DashPathEffect(new float[]{10, 5}, 0)); // Dashed lines
// Text properties
paint.setTextSize(48);
paint.setTypeface(Typeface.DEFAULT_BOLD);
paint.setTextAlign(Paint.Align.CENTER);
// Gradient effects
LinearGradient gradient = new LinearGradient(0, 0, 100, 100,
Color.RED, Color.BLUE, Shader.TileMode.CLAMP);
paint.setShader(gradient);
}
4. Drawing Basic Shapes
private void drawBasicShapes(Canvas canvas) {
// 1. Draw Line
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(3);
canvas.drawLine(50, 50, 200, 50, paint);
// 2. Draw Rectangle
paint.setColor(Color.BLUE);
paint.setStyle(Paint.Style.FILL);
canvas.drawRect(50, 100, 200, 200, paint);
// 3. Draw Rectangle with rounded corners
paint.setColor(Color.GREEN);
RectF roundRect = new RectF(250, 100, 400, 200);
canvas.drawRoundRect(roundRect, 20, 20, paint);
// 4. Draw Circle
paint.setColor(Color.RED);
canvas.drawCircle(125, 300, 50, paint);
// 5. Draw Oval
paint.setColor(Color.YELLOW);
RectF oval = new RectF(200, 250, 350, 350);
canvas.drawOval(oval, paint);
// 6. Draw Arc
paint.setColor(Color.MAGENTA);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(8);
RectF arcRect = new RectF(50, 400, 200, 550);
canvas.drawArc(arcRect, 0, 180, false, paint);
// 7. Draw Point
paint.setColor(Color.BLACK);
paint.setStrokeWidth(10);
paint.setStrokeCap(Paint.Cap.ROUND);
canvas.drawPoint(300, 450, paint);
// 8. Draw Multiple Points
float[] points = {320, 450, 340, 450, 360, 450, 380, 450};
canvas.drawPoints(points, paint);
}
5. Drawing Complex Shapes with Path
private void drawComplexShapes(Canvas canvas) {
paint.setColor(Color.BLUE);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(4);
// 1. Triangle using Path
Path trianglePath = new Path();
trianglePath.moveTo(100, 600); // Start point
trianglePath.lineTo(150, 500); // Second point
trianglePath.lineTo(200, 600); // Third point
trianglePath.close(); // Close the path
canvas.drawPath(trianglePath, paint);
// 2. Star shape
Path starPath = new Path();
starPath.moveTo(300, 550);
starPath.lineTo(320, 580);
starPath.lineTo(350, 580);
starPath.lineTo(330, 600);
starPath.lineTo(340, 630);
starPath.lineTo(300, 615);
starPath.lineTo(260, 630);
starPath.lineTo(270, 600);
starPath.lineTo(250, 580);
starPath.lineTo(280, 580);
starPath.close();
paint.setColor(Color.YELLOW);
paint.setStyle(Paint.Style.FILL);
canvas.drawPath(starPath, paint);
// 3. Curved path using quadratic Bezier
Path curvePath = new Path();
curvePath.moveTo(50, 700);
curvePath.quadTo(150, 650, 250, 700); // Control point and end point
curvePath.quadTo(350, 750, 450, 700);
paint.setColor(Color.GREEN);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(6);
canvas.drawPath(curvePath, paint);
// 4. Cubic Bezier curve
Path cubicPath = new Path();
cubicPath.moveTo(50, 800);
cubicPath.cubicTo(100, 750, 200, 850, 250, 800);
paint.setColor(Color.RED);
canvas.drawPath(cubicPath, paint);
}
6. Drawing Text
private void drawText(Canvas canvas) {
// Basic text
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.FILL);
paint.setTextSize(40);
paint.setTypeface(Typeface.DEFAULT_BOLD);
canvas.drawText("Hello Android", 100, 950, paint);
// Text with background
paint.setColor(Color.YELLOW);
paint.setStyle(Paint.Style.FILL);
Rect textBounds = new Rect();
String text = "Background Text";
paint.getTextBounds(text, 0, text.length(), textBounds);
canvas.drawRect(100, 980, 100 + textBounds.width(), 980 + textBounds.height(), paint);
paint.setColor(Color.BLACK);
canvas.drawText(text, 100, 980 + textBounds.height(), paint);
// Text on path
Path textPath = new Path();
textPath.addCircle(200, 1100, 80, Path.Direction.CW);
paint.setTextSize(24);
canvas.drawTextOnPath("Text on circular path", textPath, 0, 0, paint);
}
7. Drawing Bitmaps and Images
private void drawBitmaps(Canvas canvas) {
// Load bitmap from resources
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.sample_image);
// Draw bitmap at specific position
canvas.drawBitmap(bitmap, 400, 100, paint);
// Draw scaled bitmap
Rect srcRect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
Rect destRect = new Rect(400, 300, 600, 500);
canvas.drawBitmap(bitmap, srcRect, destRect, paint);
// Draw bitmap with matrix transformation
Matrix matrix = new Matrix();
matrix.setRotate(45, bitmap.getWidth() / 2, bitmap.getHeight() / 2);
matrix.postTranslate(400, 600);
canvas.drawBitmap(bitmap, matrix, paint);
}
8. Advanced Drawing Techniques
private void advancedDrawing(Canvas canvas) {
// 1. Gradient fills
LinearGradient linearGradient = new LinearGradient(
0, 0, 200, 200,
Color.RED, Color.BLUE,
Shader.TileMode.CLAMP
);
paint.setShader(linearGradient);
canvas.drawRect(50, 1200, 250, 1400, paint);
// 2. Radial gradient
RadialGradient radialGradient = new RadialGradient(
400, 1300, 100,
Color.YELLOW, Color.RED,
Shader.TileMode.CLAMP
);
paint.setShader(radialGradient);
canvas.drawCircle(400, 1300, 100, paint);
// 3. Pattern fill
Bitmap patternBitmap = Bitmap.createBitmap(20, 20, Bitmap.Config.ARGB_8888);
Canvas patternCanvas = new Canvas(patternBitmap);
Paint patternPaint = new Paint();
patternPaint.setColor(Color.RED);
patternCanvas.drawRect(0, 0, 10, 10, patternPaint);
patternPaint.setColor(Color.BLUE);
patternCanvas.drawRect(10, 10, 20, 20, patternPaint);
BitmapShader bitmapShader = new BitmapShader(patternBitmap,
Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
paint.setShader(bitmapShader);
canvas.drawRect(300, 1200, 500, 1400, paint);
// Reset shader
paint.setShader(null);
// 4. Shadow effects
paint.setShadowLayer(10, 5, 5, Color.GRAY);
paint.setColor(Color.BLACK);
paint.setTextSize(48);
canvas.drawText("Shadow Text", 50, 1500, paint);
paint.clearShadowLayer();
}
9. Complete Custom View Example
public class ShapeDrawingView extends View {
private Paint paint;
private Path path;
public ShapeDrawingView(Context context) {
super(context);
init();
}
private void init() {
paint = new Paint();
paint.setAntiAlias(true);
path = new Path();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Set background
canvas.drawColor(Color.WHITE);
// Draw various shapes
drawGeometricShapes(canvas);
drawCustomShapes(canvas);
drawTextAndImages(canvas);
}
private void drawGeometricShapes(Canvas canvas) {
// Implementation from previous examples
}
private void drawCustomShapes(Canvas canvas) {
// Implementation from previous examples
}
private void drawTextAndImages(Canvas canvas) {
// Implementation from previous examples
}
}
10. Using Custom View in Activity
public class DrawingActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Method 1: Set custom view directly
ShapeDrawingView drawingView = new ShapeDrawingView(this);
setContentView(drawingView);
// Method 2: Add to existing layout
// setContentView(R.layout.activity_drawing);
// LinearLayout container = findViewById(R.id.container);
// container.addView(new ShapeDrawingView(this));
}
}
Answer C: Radio Groups and Implementation in Android
Radio Groups provide a way to group RadioButtons so that only one can be selected at a time.
1. Basic Concept
RadioGroup: A container that groups RadioButton widgets, ensuring mutual exclusivity. RadioButton: Individual selectable option within a group.
2. XML Implementation
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select your favorite programming language:"
android:textSize="16sp"
android:layout_marginBottom="16dp" />
<RadioGroup
android:id="@+id/radioGroupLanguages"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:id="@+id/radioJava"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Java"
android:textSize="14sp"
android:padding="8dp" />
<RadioButton
android:id="@+id/radioPython"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Python"
android:textSize="14sp"
android:padding="8dp" />
<RadioButton
android:id="@+id/radioKotlin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Kotlin"
android:textSize="14sp"
android:padding="8dp"
android:checked="true" />
<RadioButton
android:id="@+id/radioJavaScript"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="JavaScript"
android:textSize="14sp"
android:padding="8dp" />
</RadioGroup>
<Button
android:id="@+id/buttonSubmit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"
android:layout_marginTop="16dp" />
<TextView
android:id="@+id/textViewResult"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Selected language will appear here"
android:textSize="16sp"
android:layout_marginTop="16dp"
android:background="#f0f0f0"
android:padding="12dp" />
</LinearLayout>
3. Java Implementation
public class RadioGroupActivity extends AppCompatActivity {
private RadioGroup radioGroupLanguages;
private RadioButton radioJava, radioPython, radioKotlin, radioJavaScript;
private Button buttonSubmit;
private TextView textViewResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio_group);
initializeViews();
setupEventListeners();
}
private void initializeViews() {
radioGroupLanguages = findViewById(R.id.radioGroupLanguages);
radioJava = findViewById(R.id.radioJava);
radioPython = findViewById(R.id.radioPython);
radioKotlin = findViewById(R.id.radioKotlin);
radioJavaScript = findViewById(R.id.radioJavaScript);
buttonSubmit = findViewById(R.id.buttonSubmit);
textViewResult = findViewById(R.id.textViewResult);
}
private void setupEventListeners() {
// Method 1: RadioGroup OnCheckedChangeListener
radioGroupLanguages.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton selectedRadioButton = findViewById(checkedId);
if (selectedRadioButton != null) {
String selectedText = selectedRadioButton.getText().toString();
Toast.makeText(RadioGroupActivity.this,
"Selected: " + selectedText, Toast.LENGTH_SHORT).show();
}
}
});
// Submit button listener
buttonSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getSelectedRadioButton();
}
});
}
private void getSelectedRadioButton() {
int selectedId = radioGroupLanguages.getCheckedRadioButtonId();
if (selectedId == -1) {
textViewResult.setText("No language selected");
Toast.makeText(this, "Please select a language", Toast.LENGTH_SHORT).show();
} else {
RadioButton selectedRadioButton = findViewById(selectedId);
String selectedLanguage = selectedRadioButton.getText().toString();
textViewResult.setText("Selected Language: " + selectedLanguage);
// Handle different selections
switch (selectedId) {
case R.id.radioJava:
handleJavaSelection();
break;
case R.id.radioPython:
handlePythonSelection();
break;
case R.id.radioKotlin:
handleKotlinSelection();
break;
case R.id.radioJavaScript:
handleJavaScriptSelection();
break;
}
}
}
private void handleJavaSelection() {
textViewResult.append("\nJava is great for Android development!");
}
private void handlePythonSelection() {
textViewResult.append("\nPython is excellent for data science!");
}
private void handleKotlinSelection() {
textViewResult.append("\nKotlin is Google's preferred language for Android!");
}
private void handleJavaScriptSelection() {
textViewResult.append("\nJavaScript is essential for web development!");
}
}
4. Advanced RadioGroup Implementation
public class AdvancedRadioGroupActivity extends AppCompatActivity {
private RadioGroup radioGroupDifficulty, radioGroupCategory;
private Button buttonClearSelection, buttonGetAll;
private TextView textViewResults;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_advanced_radio);
initializeViews();
setupAdvancedFeatures();
}
private void setupAdvancedFeatures() {
// Programmatically add RadioButtons
addDynamicRadioButtons();
// Set default selection
setDefaultSelections();
// Setup listeners
setupAdvancedListeners();
}
private void addDynamicRadioButtons() {
String[] categories = {"Beginner", "Intermediate", "Advanced", "Expert"};
for (int i = 0; i < categories.length; i++) {
RadioButton radioButton = new RadioButton(this);
radioButton.setText(categories[i]);
radioButton.setId(View.generateViewId());
radioButton.setPadding(8, 8, 8, 8);
// Set layout parameters
RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(
RadioGroup.LayoutParams.WRAP_CONTENT,
RadioGroup.LayoutParams.WRAP_CONTENT
);
params.setMargins(0, 8, 0, 8);
radioButton.setLayoutParams(params);
radioGroupDifficulty.addView(radioButton);
}
}
private void setDefaultSelections() {
// Set default selection for first RadioGroup
if (radioGroupDifficulty.getChildCount() > 0) {
RadioButton firstRadio = (RadioButton) radioGroupDifficulty.getChildAt(0);
firstRadio.setChecked(true);
}
}
private void setupAdvancedListeners() {
// Clear selection button
buttonClearSelection.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
radioGroupDifficulty.clearCheck();
radioGroupCategory.clearCheck();
textViewResults.setText("All selections cleared");
}
});
// Get all selections button
buttonGetAll.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getAllSelections();
}
});
// Multiple RadioGroup listeners
RadioGroup.OnCheckedChangeListener commonListener = new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
updateResults();
}
};
radioGroupDifficulty.setOnCheckedChangeListener(commonListener);
radioGroupCategory.setOnCheckedChangeListener(commonListener);
}
private void getAllSelections() {
StringBuilder results = new StringBuilder();
results.append("Current Selections:\n\n");
// Get difficulty selection
int difficultyId = radioGroupDifficulty.getCheckedRadioButtonId();
if (difficultyId != -1) {
RadioButton selectedDifficulty = findViewById(difficultyId);
results.append("Difficulty: ").append(selectedDifficulty.getText()).append("\n");
} else {
results.append("Difficulty: Not selected\n");
}
// Get category selection
int categoryId = radioGroupCategory.getCheckedRadioButtonId();
if (categoryId != -1) {
RadioButton selectedCategory = findViewById(categoryId);
results.append("Category: ").append(selectedCategory.getText()).append("\n");
} else {
results.append("Category: Not selected\n");
}
textViewResults.setText(results.toString());
}
private void updateResults() {
getAllSelections();
}
}
5. Custom RadioButton Styling
<!-- res/drawable/custom_radio_button.xml -->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true">
<shape android:shape="oval">
<solid android:color="#2196F3" />
<stroke android:width="2dp" android:color="#1976D2" />
<size android:width="20dp" android:height="20dp" />
</shape>
</item>
<item android:state_checked="false">
<shape android:shape="oval">
<solid android:color="#FFFFFF" />
<stroke android:width="2dp" android:color="#757575" />
<size android:width="20dp" android:height="20dp" />
</shape>
</item>
</selector>
<!-- Using custom style -->
<RadioButton
android:id="@+id/customRadio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Custom Radio Button"
android:button="@drawable/custom_radio_button"
android:textColor="#333333"
android:textSize="16sp"
android:padding="12dp" />
6. RadioGroup Utility Methods
public class RadioGroupUtils {
// Get selected RadioButton text
public static String getSelectedText(RadioGroup radioGroup) {
int selectedId = radioGroup.getCheckedRadioButtonId();
if (selectedId != -1) {
RadioButton selectedRadio = radioGroup.findViewById(selectedId);
return selectedRadio.getText().toString();
}
return null;
}
// Get selected RadioButton index
public static int getSelectedIndex(RadioGroup radioGroup) {
int selectedId = radioGroup.getCheckedRadioButtonId();
if (selectedId != -1) {
RadioButton selectedRadio = radioGroup.findViewById(selectedId);
return radioGroup.indexOfChild(selectedRadio);
}
return -1;
}
// Set selection by index
public static void setSelectionByIndex(RadioGroup radioGroup, int index) {
if (index >= 0 && index < radioGroup.getChildCount()) {
View child = radioGroup.getChildAt(index);
if (child instanceof RadioButton) {
((RadioButton) child).setChecked(true);
}
}
}
// Set selection by text
public static void setSelectionByText(RadioGroup radioGroup, String text) {
for (int i = 0; i < radioGroup.getChildCount(); i++) {
View child = radioGroup.getChildAt(i);
if (child instanceof RadioButton) {
RadioButton radioButton = (RadioButton) child;
if (radioButton.getText().toString().equals(text)) {
radioButton.setChecked(true);
break;
}
}
}
}
// Enable/Disable all RadioButtons
public static void setEnabled(RadioGroup radioGroup, boolean enabled) {
for (int i = 0; i < radioGroup.getChildCount(); i++) {
View child = radioGroup.getChildAt(i);
child.setEnabled(enabled);
}
}
// Get all RadioButton texts
public static List<String> getAllTexts(RadioGroup radioGroup) {
List<String> texts = new ArrayList<>();
for (int i = 0; i < radioGroup.getChildCount(); i++) {
View child = radioGroup.getChildAt(i);
if (child instanceof RadioButton) {
texts.add(((RadioButton) child).getText().toString());
}
}
return texts;
}
}
Key Features of RadioGroup:
- Mutual Exclusivity: Only one RadioButton can be selected at a time
- Event Handling: OnCheckedChangeListener for selection changes
- Programmatic Control: Can add/remove RadioButtons dynamically
- Customization: Custom styling and appearance
- Validation: Can check if any option is selected
- Multiple Groups: Can have multiple RadioGroups for different categories